package FlickrGeoTagr.Flickr {
	import com.adobe.webapis.flickr.authorization.AuthorizationView;
	import com.adobe.webapis.flickr.authorization.events.AuthorizationEvent;
	
	import flash.display.DisplayObject;
	import flash.events.*;
	import flash.net.SharedObject;
	
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;


	public class FlickrAuthorization extends EventDispatcher {
		public const API_KEY:String = "947b624e58765310fb45f684d59ceeff";
		public const SECRET:String = "cf9f53c87c865769";
		public var AuthToken:String;
		public var UserName:String;
		
		private var _sharedObject:SharedObject;
		
		public function FlickrAuthorization() {
			super();
		}
		
		public function openAuthorization(parent:DisplayObject):void {	
			if (!checkForToken()) {
				var p:IFlexDisplayObject = PopUpManager.createPopUp(parent, AuthorizationView, true);
				var auth:AuthorizationView = AuthorizationView(p);
			
				//get this from flickr
				auth.flickrAPIKey = API_KEY;
			
				//get from flickr
				auth.flickrAPISecret = SECRET;
				auth.isPopUp = false;
			
				p.addEventListener(Event.CLOSE, onAuthorizationClose);
				p.addEventListener(AuthorizationEvent.AUTHORIZATION_COMPLETE, onAuthorizationComplete);
			
				PopUpManager.centerPopUp(p);
			} else {
				this.dispatchEvent(new Event(Event.COMPLETE));
			}
		}

		public function onAuthorizationClose(e:Event):void {
			PopUpManager.removePopUp(IFlexDisplayObject(e.target));
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function onAuthorizationComplete(e:AuthorizationEvent):void {
			AuthToken = e.authToken;
			UserName = e.user.username;
			
			_sharedObject = SharedObject.getLocal("flickrAuthorization");
			_sharedObject.data.AuthToken = e.authToken;
			_sharedObject.data.UserName = e.user.username;
			_sharedObject.flush();
		}
		
		public function checkForToken():Boolean {
			_sharedObject = SharedObject.getLocal("flickrAuthorization");
			if (_sharedObject.size > 0) {
				AuthToken = _sharedObject.data.AuthToken;
				UserName = _sharedObject.data.UserName;
				return true;
			}
			return false;
		}
	}
}